using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using System.Xml.Serialization;
using System.IO.IsolatedStorage;
using System.IO;


namespace BattleCity
{
    public static class Scores
    {
        public class Score
        {
            public String name;
            public int completedLevels;

            public Score(String name, int completedLevels)
            {
                this.name = name;
                this.completedLevels = completedLevels;
            }

            public Score()
            {
                this.name = "";
                this.completedLevels = 0;
            }
           
        }

        public struct SavedScores
        {
            public List<Score> scores;
        }

        public static SavedScores savedScores;

        public static void Initialize()
        {
            #if WINDOWS_PHONE
            IsolatedStorageFile IS = IsolatedStorageFile.GetUserStoreForApplication();
            #else
            IsolatedStorageFile IS = IsolatedStorageFile.GetUserStoreForDomain();
            #endif

            if (IS.FileExists("scores.sav"))
            {
                Stream scoresfile = IS.OpenFile("scores.sav", FileMode.Open);
                XmlSerializer deserializer = new XmlSerializer(typeof(SavedScores));
                savedScores = (SavedScores)deserializer.Deserialize(scoresfile);
                scoresfile.Close();
            }
            else
            {
                savedScores = new SavedScores();
                savedScores.scores = new List<Score>();
            }
        }

        public static void Save(Score newScore)
        {
            savedScores.scores.Add(newScore);
            savedScores.scores = (savedScores.scores.OrderByDescending<Score, int>(score => score.completedLevels)).ToList<Score>();
            if (savedScores.scores.Count > 10) savedScores.scores.RemoveAt(10);

            #if WINDOWS_PHONE
            IsolatedStorageFile IS = IsolatedStorageFile.GetUserStoreForApplication();
            #else
            IsolatedStorageFile IS = IsolatedStorageFile.GetUserStoreForDomain();
            #endif

            if (IS.FileExists("scores.sav"))  IS.DeleteFile("scores.sav");

            XmlSerializer serializer = new XmlSerializer(typeof(SavedScores));
            Stream scoreFile = IS.CreateFile("scores.sav");
            serializer.Serialize(scoreFile, savedScores);
            scoreFile.Close();
        }


    }
}
